﻿//TODO: check filter, SkinFilter6

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace LowLevelGraphics.Filter
{
    /// <summary>
    /// SkinFilter6
    /// </summary>
    public class SkinFilter6 : BaseImageFilter
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="SkinFilter6"/> class.
        /// </summary>
        public SkinFilter6()
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="SkinFilter6"/> class.
        /// </summary>
        /// <param name="_skinFilter6">The _skin filter6.</param>
        internal SkinFilter6(SkinFilter6 _skinFilter6)
        {
        }

        /// <summary>
        /// Execute this Filter
        /// A Debug Statement is written if a concrete Filter is called
        /// </summary>
        /// <param name="_bitmap"></param>
        /// <returns></returns>
        public override UnsafeBitmap Execute(UnsafeBitmap _bitmap)
        {
            UnsafeBitmap bitmap = _bitmap;
            ArrayList points = new ArrayList();

            int nHeight = bitmap.Height;
            int nWidth = bitmap.Width;

            Int32 x = 0;
            Int32 y = 0;
            Color c = Color.Transparent;

            for (x = 0; x < nWidth; x++)
            {
                for (y = 0; y < nHeight; y++)
                {
                    c = bitmap.GetPixel(x, y);

                    /* convert RGB color space to IRgBy color space using this formula:
                    I= [L(R) + L(B) + L(G)] / 3
                    Rg = L(R) - L(G)
                    By = L(B) - [L(G) +L(R)] / 2
					
                    to calculate the hue:
                    hue = atan2(Rg,By) * (180 / 3.141592654f)
                    */
                    double I = (Math.Log(c.R) + Math.Log(c.B) + Math.Log(c.G)) / 3;
                    double Rg = Math.Log(c.R) - Math.Log(c.G);
                    double By = Math.Log(c.B) - (Math.Log(c.G) + Math.Log(c.R)) / 2;
                    double hue = Math.Atan2(Rg, By) * (180 / Math.PI);

                    if (I <= 5 && (hue >= 4 && hue <= 255))
                    {
                        //r = 255;
                        points.Add(new Point(x, y));
                    }
                    else
                    {
                        bitmap.SetPixel(x, y, Color.Black);
                    }
                }
            }
            return _bitmap;
        }

        /// <summary>
        /// This is used to clone a filter, each filter must implement it's own clone functionality
        /// </summary>
        /// <returns></returns>
        public override object Clone()
        {
            return new SkinFilter6(this);
        }
    }
}
